package top.kaoshanji.p1ch03a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 代码清单 p1ch03a-09：使用文件通道保存网页的示例(保存网页内容第1种写法)
 * author kaoshanji
 * ^_^
 * create time 2025/1/6 19:38
 */
public class FileChannelExample03 {

    private static final Logger logger = LogManager.getLogger(FileChannelExample03.class);

    public static void main(String[] args) {
        logger.info("...代码清单 p1ch03a-09：使用文件通道保存网页的示例(保存网页内容第1种写法)...");

        String url = "http://www.baidu.com";

        try (FileChannel destChannel = FileChannel.open(Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch03a09.txt")),
                StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {

            InputStream input = new URL(url).openStream();
            ReadableByteChannel srcChannel = Channels.newChannel(input);

            destChannel.transferFrom(srcChannel, 0, Integer.MAX_VALUE);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
